<template>
  <el-space direction="vertical">
    <h1>列表</h1>

    <el-space>
      <el-button type="default" @click="refresh">刷新</el-button>
      <el-button type="primary" @click="handleJumpAdd">新增</el-button>
    </el-space>

    <el-table v-loading="loading" :data="list" stripe border @row-dblclick="handleJumpDetail">
      <el-table-column prop="id" label="Id" width="55" />
      <el-table-column prop="title" label="标题" width="180" />
      <el-table-column prop="content" label="正文">
        <template #default="{ row }">
          <div v-html="row.content"></div>
        </template>
      </el-table-column>
    </el-table>
  </el-space>
</template>

<script lang="ts" setup>
import router from '@/router'
import axios from 'axios'
import { onMounted, ref } from 'vue'

const list = ref<NewItem[]>([])
const loading = ref(false)

/**
 * 处理跳转新增
 */
function handleJumpAdd() {
  router.push({ name: 'add' })
}

/**
 * 处理跳转详情
 */
function handleJumpDetail(row: NewItem) {
  router.push({ name: 'detail', params: { id: row.id } })
}

function refresh() {
  loading.value = true

  axios
    .get<NewItem[]>('http://localhost:3000/news', {
      params: {
        _sort: 'id', // 排序字段
        _order: 'desc' // 排序方式
      }
    })
    .then(({ data }) => {
      console.log('===', data)
      list.value = data
    })
    .finally(() => {
      loading.value = false
    })
}

onMounted(() => {
  refresh()
})
</script>
